package com.example.springioc.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.springioc.dao.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired // 注入Captcha对象
    private Captcha captcha;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        // 生成验证码（4位字符，干扰线）
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight(), captcha.getCodeCount(), captcha.getLineCount());

        // 清除缓存-老版本
        response.setHeader("Pragma", "No-cache");
        // 清除缓存-旧版本
        response.setHeader("Cache-Control", "no-cache");
        // 设置格式为图片
        response.setContentType("image/jpeg");

        // 将验证码和生成验证码时间存入session
        Long date = System.currentTimeMillis();
        session.setAttribute("captcha", lineCaptcha.getCode());
        session.setAttribute("date", date);

        // 输出验证码图片到浏览器
        lineCaptcha.write(response.getOutputStream());

        // 关闭输出流
        response.getOutputStream().close();

    }

    // 验证码校验
    @RequestMapping("/verifyCaptcha")
    public boolean verifyCaptcha(HttpSession session, String captcha) throws IOException {
        // equalsIgnoreCase()方法不区分大小写
        // 设置验证码过期时间为60s
        if(StringUtils.hasLength(captcha)
                && captcha.equalsIgnoreCase((String) session.getAttribute("captcha"))
                && (System.currentTimeMillis() - (Long) session.getAttribute("date")) < 60000) {
            return true;
        }
        return false;
    }
}
